package com.example.webflux.webflux.service.impl;

import com.example.webflux.webflux.pojo.Student;
import com.example.webflux.webflux.service.StudentService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {

    private Map<Long, Student> studentTable;

    public StudentServiceImpl() {
        this.studentTable = new HashMap<>();
        for (long i = 0L; i < 5L; i++) {
            studentTable.put(i, new Student(i, "name" + i, "address" + i, 28));
        }
    }

    @Override
    public Mono<Student> queryById(Long id) {
        return Mono.justOrEmpty(studentTable.get(id));
    }

    @Override
    public Flux<Student> queryAll() {
        Flux<Student> studentFlux = Flux.fromIterable(studentTable.values());
        return studentFlux;
    }

    @Override
    public Mono<Void> save(Mono<Student> studentMono) {
        Mono<Void> mono = studentMono.doOnNext(student -> {
            int id = studentTable.size() + 1;
            studentTable.put(Long.valueOf(String.valueOf(id)), student);
        }).thenEmpty(Mono.empty());
        return mono;
    }

    public Map<Long, Student> getStudentTable() {
        return studentTable;
    }

    public void setStudentTable(Map<Long, Student> studentTable) {
        this.studentTable = studentTable;
    }
}
